const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId;
const urlProd = 'mongodb://taosha_user:apyl8XWP6LSW4JHs@101.35.6.34:27722/taosha';
const urlTest = 'mongodb://taosha_user:apyl8XWP6LSW4JHs@150.158.169.16:27017/taosha';
const dayjs = require('dayjs');

async function main() {
  let clientProd;
  let clientTest;

  try {
    clientProd = await MongoClient.connect(urlProd, {useNewUrlParser: true, useUnifiedTopology: true});
    const dbProd = clientProd.db('taosha');
    const CustomizeModelProd = dbProd.collection('customizes');
    const MessageModelProd = dbProd.collection('messages');
    const ReplyModelProd = dbProd.collection('replies');
    const TopicModelProd = dbProd.collection('topics');
    const TopicCollectModelProd = dbProd.collection('topic_collects');
    const UserModelProd = dbProd.collection('users');

    clientTest = await MongoClient.connect(urlTest, {useNewUrlParser: true, useUnifiedTopology: true});
    const dbTest = clientTest.db('taosha');
    const CustomizeModelTest = dbTest.collection('customizes');
    const MessageModelTest = dbTest.collection('messages');
    const ReplyModelTest = dbTest.collection('replies');
    const TopicModelTest = dbTest.collection('topics');
    const TopicCollectModelTest = dbTest.collection('topic_collects');
    const UserModelTest = dbTest.collection('users');


    const query = {create_at: {$gt: dayjs().subtract(1, 'day').toDate()}};
    const queryAll = query;

    const customizes = await CustomizeModelProd.find(queryAll).toArray();
    const messages = await MessageModelProd.find(queryAll).toArray();
    const replies = await ReplyModelProd.find(queryAll).toArray();
    const topics = await TopicModelProd.find(query).toArray();
    const topic_collects = await TopicCollectModelProd.find(queryAll).toArray();
    const users = await UserModelProd.find(queryAll).toArray();

    try {
      await CustomizeModelTest.insertMany(customizes, {ordered: false});
    } catch (e) {
    }
    try {
      await MessageModelTest.insertMany(messages, {ordered: false});
    } catch (e) {
    }
    try {
      await ReplyModelTest.insertMany(replies, {ordered: false});
    } catch (e) {
    }
    try {
      await TopicModelTest.insertMany(topics, {ordered: false});
    } catch (e) {
    }
    try {
      await TopicCollectModelTest.insertMany(topic_collects, {ordered: false});
    } catch (e) {
    }
    try {
      await UserModelTest.insertMany(users, {ordered: false});
    } catch (e) {
    }

    console.log('同步数据成功...');
  } catch (e) {
    console.error(e);
  } finally {
    if (clientProd) {
      clientProd.close();
    }
    if (clientTest) {
      clientTest.close();
    }
  }


}

main();
